package com.example.demo.config.tool;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.List;

/**
 * 简单包装fastjson的常用转换方法;
 */
public class MyJson {
    public static JSONObject toJsonObject(Object o, PropertyNamingStrategy p, boolean showNullValue){
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = p;
        if(showNullValue){
            return JSONObject.parseObject(JSONObject.toJSONString(o, config, SerializerFeature.WriteMapNullValue));
        }else {
            return JSONObject.parseObject(JSONObject.toJSONString(o, config));
        }
    }

    public static <T> JSONArray toJsonArray(List<T> o, PropertyNamingStrategy p, boolean showNullValue){
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = p;
        if(showNullValue){
            return JSONArray.parseArray(JSONArray.toJSONString(o, config, SerializerFeature.WriteMapNullValue));
        }else {
            return JSONArray.parseArray(JSONArray.toJSONString(o, config));
        }
    }

    public static JSONObject toJsonObject(Object o){
        return toJsonObject(o, PropertyNamingStrategy.SnakeCase,true);
    }

    public static <T> JSONArray toJsonArray(List<T> o){
        return toJsonArray(o, PropertyNamingStrategy.SnakeCase, true);
    }

    public static JSONObject toJsonObject(Object o, PropertyNamingStrategy p){
        return toJsonObject(o, p,true);
    }
}
